﻿namespace OasisCiq.XS
{
    using System;
    using System.Xml;

    /// <summary>
    /// Represents a subset of the real numbers, 
    /// which can be represented by decimal numerals
    /// http://www.w3.org/TR/xmlschema-2/#decimal
    /// </summary>
    public class XSDecimal
    {
        public XSDecimal()
            : this(0M)
        {
        }

        public XSDecimal(decimal value)
        {
            Value = value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException">
        ///     With inner <see cref="FormatException"/> or <see cref="OverflowException"/>
        /// </exception>
        public XSDecimal(string value)
        {
            if (value == null)
            {
                throw new ArgumentNullException();
            }

            try
            {
                Value = XmlConvert.ToDecimal(value);
            }
            catch (FormatException ex)
            {
                throw new ArgumentException(ex.Message, ex);
            }
            catch (OverflowException ex)
            {
                throw new ArgumentException(ex.Message, ex);
            }
        }

        public decimal Value { get; set; }

        public static implicit operator XSDecimal(decimal argument)
        {
            return new XSDecimal(argument);
        }

        public static implicit operator decimal(XSDecimal argument)
        {
            return argument.Value;
        }

        public override string ToString()
        {
            return XmlConvert.ToString(Value);
        }
    }
}
